module StaticSite
  def self.export_site(site, path)
    archive_root = File.expand_path(File.join(RAILS_ROOT, "public", "files"))
    
    # Download a complete copy of a site and convert the links to be usable locally
    `wget -mpqEk  http://#{site}`
    
    # Parse through the css looking for background images
    if File.directory?("#{site}/css/")
      `ls -x1 #{site}/css/`.each do |file|
        # Strip newlines off of ls output
        file.gsub!(/\n/, '')
      
        # Load the whole css file into memory and join in into one string
        css_file = IO.readlines("#{site}/css/#{file}").join
      
        # Look for sections that look like url(/image/monkey.gif) and download them
        css_file.scan(/url\(([^)]+?)\)/).uniq.each do |url|
          `wget -q http://#{site}#{url}`
        end
      
        # Open the file and change the css image loads to be relative links
        File.open("#{site}/css/#{file}", "w+") do |f|
          f.puts css_file.gsub(/url\(\/?([^)]+?)\)/, "url(../\\1)")
        end
      end
    
      # Move all the images into the correct directory
      FileUtils.mv(Dir.glob(File.join("public", "*.jpg")), "#{site}/images/")
      FileUtils.mv(Dir.glob(File.join("public", "*.gif")), "#{site}/images/")
      FileUtils.mv(Dir.glob(File.join("public", "*.png")), "#{site}/images/")

      # Retain only a few copies of this file
      # if retension > 1
      #   (1...retension).each do |backup_number|
      #     backup_number = retension - backup_number
      #     p File.expand_path("#{archive_root}/archive_#{backup_number}.zip") 
      #     p File.exists?(File.expand_path("#{archive_root}/archive_#{backup_number}.zip"))
      #     if File.exists?(File.expand_path("#{archive_root}/archive_#{backup_number}.zip"))
      #       if backup_number == retension
      #         FileUtils.rm_rf("#{archive_root}/archive_#{backup_number}.zip")
      #       else
      #         FileUtils.mv("#{archive_root}/archive_#{backup_number}.zip", "#{archive_root}/archive_#{backup_number+1}.zip")
      #       end
      #     end
      #   end
      # end
    
      # Zip up all files and remove them afterwards
      `zip -r #{path} #{site}`
      FileUtils.rm_rf("#{site}")
    end
  end
end